<template>
  <div>
    <div class="__table">
      <el-button @click="dialogOpen('add')"
                 v-if="!search"
                 class="__table_button"><i class="el-icon-plus"></i></el-button>
      <s-table
        :table="table"
        ref="table"
        :control="false"
        :pagination="false"
        @http="tableWatch">
        <el-table-column
          fixed="right"
          align="center"
          slot="operation"
          class-name="operationMore"
          label="操作"
          v-if="!search"
          width="120">
          <template scope="s">
            <el-button type="success" icon="el-icon-edit" size="mini" @click="dialogOpen('PUT', s.row, s.$index)"
                       round></el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="tableDelete(s.$index, s.row)" round></el-button>
          </template>
        </el-table-column>
      </s-table>
    </div>
    <s-dialog :dialog="dialog">
      <p slot="title">
        {{dialog.title}}费用成本报销单明细
        <span v-if="dialog.title === '修改'">报销人名称：{{dialog.row.supplierName}}</span>
      </p>
      <s-form :form="formDialog" ref="formDialog">
        <el-row>
          <el-col :xs="24" :lg="{span: 11, offset: 0}">
            <el-form-item prop="supplierId" label="员工/供应商">
              <el-select v-model="formDialog.supplierId"
                         filterable
                         remote
                         :remote-method="dialogSupplierId"
                         ref="supplierId"
                         placeholder="请选择">
                <el-option
                  v-for="item in dialog.supplierId"
                  :key="item.id"
                  :label="item.bxSupplierName + '   ' + item.bxSupplierDepartmentname + '   ' + item.bxSupplierDepartmentid"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :lg="{span: 11, offset: 1}">
            <el-form-item prop="departmentId" label="费用所属部门">
              <el-cascader
                :options="dialog.departmentId"
                v-model="formDialog.departmentId"
                :show-all-levels="false"
                ref="departmentId"
                clearable
                filterable
                change-on-select
                :props="{
                  value: 'key',
                }"
                placeholder="所属部门"
              ></el-cascader>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :xs="24" :lg="{span: 4, offset: 0}">
            <el-form-item prop="costProject" label="费用项目 ">
              <el-input
                type="text"
                v-model="formDialog.costProject"
                placeholder="费用项目 "></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :lg="{span: 4, offset: 1}">
            <el-form-item prop="category" label="类别">
              <el-select v-model="formDialog.category"
                         ref="category"
                         placeholder="请选择">
                <el-option
                  v-for="item in EXPENSE.category"
                  :key="item.id"
                  :label="item.text"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :lg="{span: 4, offset: 1}">
            <el-form-item prop="reimbursementProportion" label="报销比例">
              <el-input
                type="text"
                v-model="formDialog.reimbursementProportion"
                placeholder="报销比例">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :lg="{span: 4, offset: 1}">
            <el-form-item prop="settlementCycle" label="归属周期">
              <el-date-picker
                v-model="formDialog.settlementCycle"
                type="month"
                format="yyyy年 MM月"
                placeholder="选择日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :lg="{span: 3, offset: 1}">
            <el-form-item prop="money" label="金额">
              <el-input
                type="text"
                v-model.number="formDialog.money"
                placeholder="金额"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :xs="24" :lg="{span: 5, offset: 0}">
            <el-form-item prop="isLoan" label="是否借款">
              <el-select v-model="formDialog.isLoan" placeholder="请选择">
                <el-option label="是" :value="2"></el-option>
                <el-option label="否" :value="1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :lg="{span: 5, offset: 1}" v-if="formDialog.isLoan === 2">
            <el-form-item prop="loanId" label="借款单">
              <el-select v-model="formDialog.loanId"
                         remote
                         ref="loanId"
                         filterable
                         @change="dialogLoanIdChange"
                         :remote-method="dialogLoanId"
                         placeholder="请选择">
                <el-option
                  v-for="item in dialog.loanId"
                  :key="item.id"
                  :label="item.loanProject + '   ' + item.reimbursementCode + '  ' + item.loanSurplusMoney"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :lg="{span: 5, offset: 1}" v-if="formDialog.isLoan === 2">
            <el-form-item prop="loanNum1" label="剩余最大借款数">
              <el-input v-model="dialog.maxLoanNum" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :lg="{span: 5, offset: 1}" v-if="formDialog.isLoan === 2">
            <el-form-item prop="loanState" label="借款单是否全部冲销">
              <div class="s-content">
                <el-switch
                  v-model="formDialog.loanState"
                  :disabled="dialog.maxLoanNum < formDialog.money"
                  :active-value="2"
                  :inactive-value="1"
                  active-text="是"
                  inactive-text="否">
                </el-switch>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </s-form>
      <el-button slot="footer" @click="dialogSave">保存</el-button>
    </s-dialog>
  </div>
</template>

<script>
  /* eslint-disable semi,no-trailing-spaces */

  import {AutoVue, AutoPromise, SplitK} from '~/plugins/Tools';

  let id = 0;
  /**
   * 报销单明细
   category (string, optional): 类别$$$true$true$false$$4$vNull,
   costProject (string, optional): 费用项目 $$$true$true$false$$2$vNull,
   id (string, optional),
   isLoan (integer, optional): 是否借款$$$true$true$false$$7$vNull,
   loanId (string, optional): 借款单$$$true$true$false$$8$vNull,
   loanNum (number, optional): 借款数$$$true$true$false$$9$vNull,
   money (number, optional): 金额$$$true$true$false$$6$vNull,
   reimbursementProportion (string, optional): 报销比例$$$true$true$false$$5$vNull,
   settlementCycle (string, optional): 结算归属周期$$$true$true$false$$3$vNull,
   supplierId (string, optional): 报销人$$$true$true$false$$1$vNull,
   */
  function treefilter (arrayTree) {
    if (typeof arrayTree === 'undefined') return undefined;
    let tree = [];
    arrayTree.forEach(item => {
      if (item.children && item.children.length === 0) {
        delete item.children;
      } else {
        item.children = treefilter(item.children);
      }
      delete item.disabled;
      tree.push(item);
    });
    return tree;
  }

  function __formDialog () {
    return {
      supplierId: { value: '', rule: [ 'vNull__change' ] },
      departmentId: { value: [], rule: [ 'vNull__change' ] },
      costProject: { value: '', rule: [ 'vNull' ] },
      settlementCycle: { value: new Date(), rule: [ 'vNull__change' ], type: 'Date' },
      category: { value: '', rule: [ 'vNull__change' ] },
      reimbursementProportion: { value: '', rule: [] },
      money: { value: 0, rule: [ 'vNull', 'vNumber', 'vN0Number' ] },
      isLoan: { value: 1, rule: [ 'vNull' ] },
      loanId: { value: '', rule: [ 'vNull__change' ] },
      loanState: { value: 1, rule: [ 'vNull__change' ] },
      loanNum: { value: 0, rule: [ 'vNull', 'vNumber' ] } };
  }

  function tofixed (dt) {
    dt += '';
    let result;
    if (dt.indexOf('.') !== -1) {
      result = dt.substr(0, dt.indexOf('.') + 3);
    } else {
      result = dt;
    }
    return parseFloat(result);
  }

  export default AutoVue({
    name: 'expense',
    data: {
      table: {
        column: [
          {'label': '收款方', 'prop': 'supplierName', 'minWidth': '0px'},
          {'label': '费用所属部门', 'prop': 'departmentName', 'minWidth': '200px'},
          {
            'label': '费用项目 ',
            'prop': 'costProject',
            'minWidth': '0px',
          }, {'label': '归属周期',
            formatter: (row, column) => {
              return this.a.methods.formatterTime(row[column.property || column], 22);
            },
            'prop': 'settlementCycle',
            'minWidth': '110px'}, {
            'label': '类别',
            'prop': 'categoryName',
            'minWidth': '0px',
          }, {'label': '报销比例',
            'prop': 'reimbursementProportion',
            'minWidth': '0px'},
          {
            'label': '金额',
            'prop': 'money',
            formatter: (row, column) => {
              return SplitK(row[column.property || column]);
            },
            'minWidth': '0px',
          },
          {
            'label': '是否借款',
            'prop': 'isLoan',
            'minWidth': '0px',
            formatter: (row, column) => {
              return parseInt(row[column.property || column]) === 1 ? '否' : '是';
            },
          },
          {'label': '借款单', 'prop': 'loanCode', 'minWidth': '0px'},
          {
            'label': '全部冲销',
            'prop': 'loanState',
            formatter: (row, column) => {
              return parseInt(row[column.property || column]) === 1 ? '否' : '是';
            },
            'minWidth': '0px',
          },
        ],
        key: 'id',
        muti: false,
      },
      formDialog: __formDialog(),
      dialog: {
        modal: false,
        title: '新增',
        width: '80%',
        maxLoanNum: 0,
        dialogCallBack: function () {
          this.formDialog.loanId = '';
          this.formDialog.loanNum = 0;
        },
        row: {},
        index: '',
        editLock: 0,
        supplierId: [],
        departmentId: [],
        settlementCycle: [],
        loanId: [],
      },
    },
    props: {
      init: {
        type: Array,
      },
      search: {
        type: Boolean,
        default: false,
      },
      row: {
        type: Object,
        default () {
          return {};
        },
      },
    },
    store: ['EXPENSE', 'DICTIONARY_expense'],
    computed: {},
    watch: {
      'formDialog.supplierId': function (id) {
        if (!id) return;
        if (this.editLock > 0) {
          this.editLock--;
          return;
        }
        this.$nextTick(async () => {
          let departmentIds = this.$refs.supplierId.selectedLabel.split('   ');
          this.$set(this.formDialog, 'departmentId', await this.get('/dictionaries/departmentIds/' + departmentIds[departmentIds.length - 1]));
        });
      },
      'formDialog.money': function (money) {
        if (!money) return;
        if (!this.formDialog.loanId) return;
        if (money > this.dialog.maxLoanNum) {
          this.formDialog.loanState = 2;
        }
      },
    },
    methods: {
      tableDelete (index, row) {
        let tableRef = 'table';
        this.$confirm('您将删除该条明细。', '确认删除？', {
          confirmButtonText: '是',
          cancelButtonText: '否',
          type: 'warning',
        }).then(async () => {
          this[tableRef].data.splice(index, 1);
          this.$emit('change', this.table.data);
        });
      },
      dialogLoanIdChange (val) {
        let loanId = this.dialog.loanId.find((item) => {
          return item.id === val;
        });
        this.dialog.maxLoanNum = parseFloat(loanId.loanSurplusMoney);
        if (this.dialog.maxLoanNum < this.formDialog.money) {
          this.formDialog.loanState = 2;
        } else {
          this.formDialog.loanState = 1;
        }
      },
      async dialogSupplierId (query = '') {
        this.dialog.supplierId = await this.post('/supplier/get', {
          name: query,
        });
      },
      async dialogLoanId (query = '') {
        let {contentList} = await this.post('/borrowing/searchToCost/' + (this.row.id || 1), {
          bxSetlecycleName: query,
          'pageNumber': 1,
          'pageSize': 20});
        this.dialog.loanId = contentList;
      },
      dialogOpen (type, more, index) {
        if (type) {
          type = type.toUpperCase();
        } else return;
        AutoPromise([
          async () => {
            let json = await this.get('/dictionaries/getDepartmentTree');
            this.dialog.departmentId = treefilter(json);
          },
          async () => {
            if (more && !more.departmentIdOld) {
              more.departmentIdOld = await this.get('/dictionaries/departmentIds/' + more.departmentId);
            }
          },
          async () => {
            if (!this.DICTIONARY_expense) {
              await this.USE('DICTIONARY_expense');
            }
          },
          async () => {
            await this.dialogSupplierId(more ? more.supplierName : '');
          },
          async () => {
            await this.dialogLoanId();
          },
        ]);
        switch (type) {
        case 'ADD':
          this.dialog.title = '新增';
          this.formDialog.id = 0;
          break;
        case 'PUT':
          this.dialog.title = '修改';
          this.editLock = 1;
          this.$nextTick(() => {
            this.formDialog = {
              ...this.formDialog,
              ...this.ObjectClone(__formDialog(), more),
            };
            this.formDialog.departmentId = more.departmentIdOld;
            if (this.formDialog.loanId) {
              let loanId = this.dialog.loanId.find((item) => {
                return item.id === this.formDialog.loanId;
              });
              this.dialog.maxLoanNum = parseFloat(loanId.loanSurplusMoney);
            }
          });
          this.dialog.row = more;
          this.dialog.index = index;
          break;
        }
        this.dialog.visible = true;
      },
      dialogSave: function () {
        this.VALIDATE('formDialog', option => {
          option.id = id++;
          option.supplierName = this.$refs.supplierId.selectedLabel.split('   ')[0];
          option.categoryName = this.$refs.category.selectedLabel;
          option.departmentId = option.departmentId[option.departmentId.length - 1];
          option.departmentName = this.$refs.departmentId.currentLabels.join('-');

          if (option.money !== 0 && option.money !== '') {
            option.money = tofixed(option.money);
          }
          if (option.isLoan === 2) {
            option.loanCode = this.$refs.loanId.selectedLabel.split('   ')[0]
            if (option.loanState === 2) {
              option.loanNum = this.dialog.maxLoanNum
            } else {
              option.loanNum = option.money
            }
          } else {
            option.loanCode = '无'
            option.loanId = ''
            option.loanNum = 0
            option.loanState = 1
          }
          if (this.dialog.index === '') {
            this.table.data.push(option)
          } else {
            this.table.data.splice(this.dialog.index, 1)
            this.table.data.unshift(option)
          }
          this.$emit('change', this.table.data)
          this.dialog.dialogInit.call(this)
        })
      },
    },
    mounted: function () {
      console.log(this);
      if (this.init && this.init.length !== 0) {
        let step = [];
        this.init.forEach(item => {
          step.push({
            ...item,
          });
        });
        this.table.data = step;
        this.$emit('change', this.table.data, 1);
      }
    },
  });
</script>

<style scoped lang="scss">
  .card {
    float: left;
    border-radius: 3px;
    box-shadow: 0 2px 10px 1px rgba(0, 0, 0, .1);
    height: 110px;
    width: 300px;
    margin: 15px;
    padding: 25px;
    position: relative;
    vertical-align: top;
    transition: .4s;
    cursor: pointer;
    &:hover {
      box-shadow: 0 10px 20px 1px rgba(0, 0, 0, .1);
      text-decoration: none;
    }
  }

  .card__icon {
    font-size: 24px;
    left: 28px;
    position: absolute;
    top: 25px;
    color: #20a0ff;
  }

  .card__title {
    color: #20a0ff;
    margin-top: 0;
    margin-bottom: 10px;
    margin-left: 40px;
  }

  .card__body {
    line-height: 22px;
    margin-left: 40px;
  }

  @media screen and (max-width: 800px) {
    .card {
      width: calc(100% - 80px);
    }
  }
</style>
